package protocol;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Random;

import protocol.xml.XmlBuilder;

public class AnnouncingThread extends Thread {

	private boolean announcingGame;
	private XmlBuilder announcingGameXml;
	private InetAddress broadcastIP;
	private DatagramSocket sendingDatagram;

	public AnnouncingThread(XmlBuilder announcingGameXml, InetAddress broadcastIP, DatagramSocket sendingDatagram) {
		this.announcingGame = true;
		this.announcingGameXml = announcingGameXml;
		this.broadcastIP = broadcastIP;
		this.sendingDatagram = sendingDatagram;
	}

	public void stopAnnouncing() {
		announcingGame = false;
	}

	@Override
	public void run() {
		final byte[] buf = announcingGameXml.toString().getBytes();


		// Aleatorio para el time out
		Random ale = new Random();

		while(announcingGame && announcingGameXml != null) {

			try {
				sendingDatagram.send(new DatagramPacket(buf, buf.length, broadcastIP, ConnectionDiscover.MULTICAST_PORT));
			} catch (IOException e) {
				Print.print("AnnouncingThread-IOException");
			}

			// Tiempo por fuera para no congestionar la red
			try{Thread.sleep(250 + ale.nextInt(100));}catch(InterruptedException ie){}
		}
	}

}
